<template>
  <demo-content :title="title">
    <p>
      HTML5 应用程序是以事件来驱动的。可以在 HTML
      元素上注册事件监听器，并编写用于响应这些事件的实现代码。几乎所有基于
      Canvas
      的应用程序都会处理鼠标或触摸事件，有些程序则两种事件都会处理，还有许多程序会处理其他各种类型的事件，如键盘事件、拖放事件。
    </p>
    <p>
      事件统计：
      <ul>
        <li>鼠标点击(mousedown): {{ mousedownCnt }}
          <ul>
            <li>鼠标左键: {{ mouseLeftBtnDownCnt }}</li>
            <li>鼠标右键: {{ mouseRightBtnDownCnt }}</li>
            <li>鼠标中键: {{ mouseMidBtnDownCnt }}</li>
          </ul>
        </li>
        <li>
          鼠标抬起(mouseup): {{ mouseupCnt }}
        </li>
        <li>
          鼠标移动(mousemove): {{ mousemoveCnt }}
        </li>
        <li>
          鼠标移出(mouseout): {{ mouseoutCnt }}
        </li>
        <li>
          鼠标双击(mousedblclick): {{ mouseDblClickCnt }}
        </li>
      </ul>
      <em>鼠标右键事件对应的 mouseup 不会被捕捉到。</em>
    </p>
    <canvas ref="canvasRef"></canvas>
  </demo-content>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";

const title = "事件处理";
// 指定组件上的属性
defineOptions({ title });;
const mousedownCnt = ref(0);
const mouseLeftBtnDownCnt = ref(0);
const mouseMidBtnDownCnt = ref(0);
const mouseRightBtnDownCnt = ref(0);
const mouseupCnt = ref(0);
const mousemoveCnt = ref(0);
const mouseoutCnt = ref(0);
const mouseDblClickCnt = ref(0);

const canvasRef = ref<HTMLCanvasElement>();
onMounted(() => {
  const canvas = canvasRef.value!;
  const ctx = canvas.getContext("2d")!;
  ctx.fillText("hello", 0, 10);
  canvas.onmousedown = (e) => {
    // 鼠标按下事件处理
    mousedownCnt.value += 1;
    if (e.button === 0) {
      // 主按键，通常为鼠标左键
      mouseLeftBtnDownCnt.value += 1;
    } else if (e.button === 1) {
      // 辅助按键，通常为鼠标滚轮中键
      mouseMidBtnDownCnt.value += 1;
    } else if (e.button === 2) {
      // 次按键，通常为鼠标右键
      mouseRightBtnDownCnt.value += 1;
    }
  }
  canvas.onmouseup = (_e) => {
    mouseupCnt.value += 1
  }
  canvas.onmousemove = (_e) => {
    mousemoveCnt.value += 1;
  }
  canvas.onmouseout = (_e) => {
    mouseoutCnt.value += 1;
  }
  // 等价于 canvas.ondblclick = ...
  canvas.addEventListener('dblclick', (_e) => {
    mouseDblClickCnt.value += 1;
  })
});
</script>

<style src="./default.css" scoped></style>
